#include "DesktopEventsThread.h"

#include "../components/MainComponent.h"


DesktopEventsThread::DesktopEventsThread(const String &threadName) : Thread (threadName),
																	 startTime (-1),
																	 changingState (false),
																	 hidden(true),
																	 shouldBeHidden(true),
																	 timeline (0)
{
	timeline = new TimelineSystem (0.8f/*smoothFactor*/,2/*loopcount*/);
}
DesktopEventsThread::~DesktopEventsThread()
{
	stopThread(100);
	if(timeline)
		delete timeline;
}

void DesktopEventsThread::run()
{
	while (! threadShouldExit())
	{
		if(shouldBeHidden)
		{
			if(!changingState)
			{
				int x, y;
					Desktop::getMousePosition(x, y);

				if(hidden)
				{
					if(y==0)
					{
						if(startTime == -1)
							startTime = Time::getMillisecondCounter();

						if(Time::getMillisecondCounter() - startTime > 1000)
						{
							const MessageManagerLock mmLock;

							changingState = true;

							ResizableWindow * rw = dynamic_cast<ResizableWindow*> (TopLevelWindow::getActiveTopLevelWindow());
								
							SliceActionChain* chain1 = new SliceActionChain();
							chain1->addAction(
									new ComponentEffectPosition(rw, Point((float)rw->getX(), 0.0f)),
									500, /*milliseconds*/
									TransitionLinear::stepToNextFrame
							);
							
							timeline->addChain(chain1);
							timeline->play(); 
						}
					}
					else
					{
						startTime = -1;
					}
				} else
				{
					if(Desktop::getInstance().findComponentAt(x, y) == 0)
					{
						if(startTime == -1)
							startTime = Time::getMillisecondCounter();

						if(Time::getMillisecondCounter() - startTime > 1000)
						{
							const MessageManagerLock mmLock;

							changingState = true;

							ResizableWindow * rw = dynamic_cast<ResizableWindow*> (TopLevelWindow::getActiveTopLevelWindow());
								
							SliceActionChain* chain1 = new SliceActionChain();
							chain1->addAction(
									new ComponentEffectPosition(rw, Point((float)rw->getX(), (float)-rw->getHeight())),
									500, /*milliseconds*/
									TransitionLinear::stepToNextFrame
							);
							
							timeline->addChain(chain1);
							timeline->play(); 
						}
					}
					else
					{
						startTime = -1;
					}

				}
			} else
			{
				//is already changing state
				if(!timeline->isPlaying())
				{
					changingState = false;

					hidden = !hidden;

					startTime = -1;
				}
			}

		}
	}
}